var target_admin = function () {
  "use strict"

  var layoutColors = ['#16a085', '#e74c3c', '#428bca', '#333333', '#6685a4', '#E68E8E']
  
  return { init: init, layoutColors: layoutColors, debounce: debounce }

  function init () {    
    initLayoutToggles ()  
    initNoticeBar ()

    navHoverInit ({ delay: { show: 250, hide: 350 } })

    initICheck ()
    initSelect2 ()
    initTableCheckable ()
    
    initScrollable ()
    initLightbox ()
    initEnhancedAccordion ()
    initDataTableHelper ()

    initFormValidation ()
    initTooltips ()
    initDatepicker ()
    initTimepicker ()
    initColorpicker ()
    initAutosize ()

    initBackToTop ()
  }

  function initScrollable () {
    if ($.fn.niceScroll) {
      $('.scrollable-panel').niceScroll ()
    }
  }

  function isLayoutCollapsed () {
    return $('.navbar-toggle').css ('display') == 'block'
  }

  function initLayoutToggles () {
    $('.navbar-toggle, .mainnav-toggle').click (function (e) {
      $(this).toggleClass ('is-open')
    })
  }

  function initNoticeBar () {
    $('.noticebar > li > a').click (function (e) {
      if (isLayoutCollapsed ()) {
        window.location = $(this).prop ('href')
      }
    })
  }

  function navHoverInit (config) {
    $('[data-hover="dropdown"]').each (function () {
      var $this = $(this),
          defaults = { delay: { show: 1000, hide: 1000 } },
          $parent = $this.parent (),
          settings = $.extend (defaults, config),
          timeout

      if (!('ontouchstart' in document.documentElement)) {
        $parent.find ('.dropdown-toggle').click (function (e) {
            if (!isLayoutCollapsed ()) {
              e.preventDefault ()
              e.stopPropagation ()
            }
        })
      }

      $parent.mouseenter(function () {
        if (isLayoutCollapsed ()) { return false }

        timeout = setTimeout (function () {
          $parent.addClass ('open')
          $parent.trigger ('show.bs.dropdown')
        }, settings.delay.show)
      })

      $parent.mouseleave(function () {
        if (isLayoutCollapsed ()) { return false }

        clearTimeout (timeout)

        timeout = setTimeout (function () {
          $parent.removeClass ('open keep-open')
          $parent.trigger ('hide.bs.dropdown')
        }, settings.delay.hide)
      })
    })
  }

  function initTableCheckable () {
    if ($.fn.tableCheckable) {
      $('.table-checkable')
            .tableCheckable ()
              .on ('masterChecked', function (event, master, slaves) { 
                  if ($.fn.iCheck) { $(slaves).iCheck ('update') }
              })
              .on ('slaveChecked', function (event, master, slave) {
                  if ($.fn.iCheck) { $(master).iCheck ('update') }
              })
    }
  }

  function initAutosize () {
    if ($.fn.autosize) {
    $('.ui-textarea-autosize').each(function() {
      if($(this).data ('animate')) {
          $(this).addClass ('autosize-animate').autosize()
        } else {
          $(this).autosize()
        }
      })
    }
  }

  function initEnhancedAccordion () {
    $('.accordion .accordion-toggle').on('click', function (e) {      
      $(e.target).parent ().parent ().parent ().addClass('open')
    })
  
    $('.accordion .accordion-toggle').on('click', function (e) {
      $(this).parents ('.panel').siblings ().removeClass ('open')
    })

    $('.accordion').each (function () {       
      $(this).find ('.panel-collapse.in').parent ().addClass ('open')
    })     
  }

  function initFormValidation () {
    if ($.fn.parsley) {
      $('.parsley-form').each (function () {
        $(this).parsley ({
          trigger: 'change',
          errors: {
            container: function (element, isRadioOrCheckbox) {
              if (element.parents ('form').is ('.form-horizontal')) {
                return element.parents ("*[class^='col-']")
              }

              return element.parents ('.form-group')
            }
          }
        })
      })
    }
  }

  function initLightbox () {
    if ($.fn.magnificPopup) {
      $('.ui-lightbox').magnificPopup({
        type: 'image',
        closeOnContentClick: false,
        closeBtnInside: true,
        fixedContentPos: true,
        mainClass: 'mfp-no-margins mfp-with-zoom', // class to remove default margin from left and right side
        image: {
          verticalFit: true,
          tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
        }
      })

      $('.ui-lightbox-video, .ui-lightbox-iframe').magnificPopup({
        disableOn: 700,
        type: 'iframe',
        mainClass: 'mfp-fade',
        removalDelay: 160,
        preloader: false,
        fixedContentPos: false
      })

      $('.ui-lightbox-gallery').magnificPopup({
        delegate: 'a',
        type: 'image',
        tLoading: 'Loading image #%curr%...',
        mainClass: 'mfp-img-mobile',
        gallery: {
          enabled: true,
          navigateByImgClick: true,
          preload: [0,1] // Will preload 0 - before current, and 1 after the current image
        },
        image: {
          tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
          titleSrc: function(item) {
            return item.el.attr('title') + '<small>by Marsel Van Oosten</small>'
          }
        }
      })
    }
  }

  function initSelect2 () {
    if ($.fn.select2) {
      $('.ui-select2').select2({ allowClear: true, placeholder: "Select..." })
    }
  }

  function initDatepicker () {
    if ($.fn.datepicker) { $('.ui-datepicker').datepicker ({ autoclose: true }) }
  }

  function initTimepicker () {
    if ($.fn.timepicker) { 
      var pickers = $('.ui-timepicker, .ui-timepicker-modal')

      pickers.each (function () {
        $(this).parent ('.input-group').addClass ('bootstrap-timepicker')

        if ($(this).is ('.ui-timepicker')) {
          $(this).timepicker ()
        } else {
          $(this).timepicker({ template: 'modal' })
        } 
      })   
    }
  }

  function initColorpicker () {
    if ($.fn.simplecolorpicker) {
      $('.ui-colorpicker').each (function (i) {
        var picker = $(this).data ('picker')

        $(this).simplecolorpicker({ 
          picker: picker
        })
      })
    }
  }

  function initTooltips () {
    if ($.fn.tooltip) { $('.ui-tooltip').tooltip () }
    if ($.fn.popover) { $('.ui-popover').popover ({ container: 'body' }) }
  }

  function initICheck () {
    if ($.fn.iCheck) {
      $('.icheck-input').iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue',
        inheritClass: true
      }).on ('ifChanged', function (e) {
        $(e.currentTarget).trigger ('change')
      })
    }
  }

  function initBackToTop () {
    var backToTop = $('<a>', { id: 'back-to-top', href: '#top' })
    var icon = $('<i>', { class: 'fa fa-chevron-up' })

    backToTop.appendTo ('body')
    icon.appendTo (backToTop)
    
      backToTop.hide()

      $(window).scroll(function () {
          if ($(this).scrollTop() > 150) {
              backToTop.fadeIn ()
          } else {
              backToTop.fadeOut ()
          }
      })

      backToTop.click (function (e) {
        e.preventDefault ()

          $('body, html').animate({
              scrollTop: 0
          }, 600)
      })
  }

  function initDataTableHelper () {
    if ($.fn.dataTable) {
      $('[data-provide="datatable"]').each (function () { 
        $(this).addClass ('dataTable-helper')    
        var defaultOptions = {
            paginate: false,
            search: false,
            info: false,
            lengthChange: false,
            displayRows: 10
          },
          dataOptions = $(this).data (),
          helperOptions = $.extend (defaultOptions, dataOptions),
          $thisTable,
          tableConfig = {}

        tableConfig.iDisplayLength = helperOptions.displayRows
        tableConfig.bFilter = true
        tableConfig.bSort = true
        tableConfig.bPaginate = false
        tableConfig.bLengthChange = false  
        tableConfig.bInfo = false

        if (helperOptions.paginate) { tableConfig.bPaginate = true }
        if (helperOptions.lengthChange) { tableConfig.bLengthChange = true }
        if (helperOptions.info) { tableConfig.bInfo = true }       
        if (helperOptions.search) { $(this).parent ().removeClass ('datatable-hidesearch') }       

        tableConfig.aaSorting = []
        tableConfig.aoColumns = []

        $(this).find ('thead tr th').each (function (index, value) {
          var sortable = ($(this).data ('sortable') === true) ? true : false
          tableConfig.aoColumns.push ({ 'bSortable': sortable })

          if ($(this).data ('direction')) {
            tableConfig.aaSorting.push ([index, $(this).data ('direction')])
          }
        })   
        
        // Create the datatable
        $thisTable = $(this).dataTable (tableConfig)

        if (!helperOptions.search) {
          $thisTable.parent ().find ('.dataTables_filter').remove ()
        }

        var filterableCols = $thisTable.find ('thead th').filter ('[data-filterable="true"]')

        if (filterableCols.length > 0) {
          var columns = $thisTable.fnSettings().aoColumns,
            $row, th, $col, showFilter

          $row = $('<tr>', { cls: 'dataTable-filter-row' }).appendTo ($thisTable.find ('thead'))

          for (var i=0; i<columns.length; i++) {
            $col = $(columns[i].nTh.outerHTML)
            showFilter = ($col.data ('filterable') === true) ? 'show' : 'hide'

            th = '<th class="' + $col.prop ('class') + '">'
            th += '<input type="text" class="form-control input-sm ' + showFilter + '" placeholder="' + $col.text () + '">'
            th += '</th>'
            $row.append (th)
          }

          $row.find ('th').removeClass ('sorting sorting_disabled sorting_asc sorting_desc sorting_asc_disabled sorting_desc_disabled')

          $thisTable.find ('thead input').keyup( function () {
            $thisTable.fnFilter( this.value, $thisTable.oApi._fnVisibleToColumnIndex( 
              $thisTable.fnSettings(), $thisTable.find ('thead input[type=text]').index(this) ) )
          })

          $thisTable.addClass ('datatable-columnfilter')
        }
      })

      $('.dataTables_filter input').prop ('placeholder', 'Search...')
    }
  }

  function debounce (func, wait, immediate) {
    var timeout, args, context, timestamp, result
    return function() {
      context = this
      args = arguments
      timestamp = new Date()

      var later = function() {
        var last = (new Date()) - timestamp

        if (last < wait) {
          timeout = setTimeout(later, wait - last)
        } else {
          timeout = null
          if (!immediate) result = func.apply(context, args)
        }
      }

      var callNow = immediate && !timeout

      if (!timeout) {
        timeout = setTimeout(later, wait)
      }

      if (callNow) result = func.apply(context, args)
      return result
    }
  }
}()

function getPageNotifications() {
    $.ajax({
    url: BASEURL + '/page-notifications',
    dataType: "json",
    beforeSend:function(){
      $('#fbpage-noti').append('<li id="loading">Loading..</li>');
    },
    success: function(rs) {
      $('#fbpage-noti #loading').hide();
      if(rs.length <= 0) return;
      unreadMsg = '';
      for(i in rs) {
        if(rs[i].unread > 0) {
          unreadMsg = ' <span class="badge">'+rs[i].unread+'</span>';
        }
        else {
          unreadMsg = '';
        }
        $('#fbpage-noti').append('<li data-id="'+rs[i]['page_info']['fb_page_id']+'"><a data-toggle="modal" href="#pagenoti-'+rs[i]['page_info']['fb_page_id']+'"><img src="//graph.facebook.com/'+rs[i]['page_info']['fb_page_id']+'/picture" class="navbar-profile-avatar" alt=""> '+rs[i]['page_info']['page_name']+unreadMsg+'</a></li>');
        $('body').append('<div id="pagenoti-'+rs[i]['page_info']['fb_page_id']+'" class="page-noti modal modal-styled fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3 class="modal-title">'+rs[i]['page_info']['page_name']+'</h3></div><div class="modal-body"><ul class="icons-list notifications-list"></ul></div><!-- /.modal-content --><div class="modal-footer"><button type="button" class="btn btn-tertiary" data-dismiss="modal">Close</button></div></div><!-- /.modal-dialog --></div><!-- /.modal -->');

          // append notifications
          for(j in rs[i]['notifications']) {
            $('#pagenoti-'+rs[i]['page_info']['fb_page_id']+' ul.notifications-list').append('<li id="nitem-'+rs[i]['notifications'][j]['id']+'"><a href="'+rs[i]['notifications'][j]['link']+'" target="_blank"><i class="icon-li fa fa-bell-o"></i> '+rs[i]['notifications'][j]['title']+'<span class="noticebar-item-time"><i class="fa fa-clock-o"></i> '+rs[i]['notifications'][j]['created_time']+'</span></a></li>');
            if(rs[i]['notifications'][j]['unread'] == 1) {
              $('#nitem-'+rs[i]['notifications'][j]['id']).css('background', '#dfe3ee');
            }
            else{
              $('#nitem-'+rs[i]['notifications'][j]['id']).css('background', 'none');
            }
          }
      }
    },
    error:function() {
      $('#fbpage-noti #loading').html('Error when loading page data');
      $('#fbpage-noti #loading').show();
    }
  });

}
function unixToDate(unix) {
  var month = new Array();
  month[0] = "January";
  month[1] = "February";
  month[2] = "March";
  month[3] = "April";
  month[4] = "May";
  month[5] = "June";
  month[6] = "July";
  month[7] = "August";
  month[8] = "September";
  month[9] = "October";
  month[10] = "November";
  month[11] = "December";
  // var n = month[d.getMonth()];

  var date = new Date(unix*1000);
  var year = date.getFullYear();
  var fullMonth = month[date.getMonth()];
  var day = date.getDay();

  var hours = date.getHours();
  var minutes = "0" + date.getMinutes();
  var seconds = "0" + date.getSeconds();
  var formattedTime = hours + ':' + minutes.substr(minutes.length-2) + ' ' + year + ' ' + fullMonth + ' ' + day;
  return formattedTime;
}
var Notify = {
  nodeServer: null,
  userChannel: null,
  setStatus: function(status) {
    console.log(status);
  },
  init: function(params) {
    this.nodeServer = params.nodeServer;
    this.userChannel = params.userChannel;
  },
  run: function() {
    if(typeof io == 'undefined') return;
    var socket = io.connect(this.nodeServer);
    var self = this;

    socket.on('connect', function(data) {
      self.setStatus('connected');
      socket.emit('subscribe', {channel: self.userChannel});
    });
    socket.on('notification', function(data) {
      obj = $.parseJSON(data.data);
      console.log(obj);
      if(typeof obj.changes != 'undefined') {
        strAct = '';
        link = '';

        for(i in obj.changes) {
          // not display notification for 'remove' action(unlike, remove comment..)
          if(obj.changes[i]['value']['verb'] == 'remove') return;
          if(typeof obj.changes[i]['value']['sender_id'] != 'undefined') {
            strAct = '<img class="navbar-profile-avatar" src="//graph.facebook.com/'+obj.changes[i]['value']['sender_id']+'/picture"> ';
          }
          else if(typeof obj.changes[i]['value']['user_id'] != 'undefined') {
            strAct = '<img class="navbar-profile-avatar" src="//graph.facebook.com/'+obj.changes[i]['value']['user_id']+'/picture"> ';
          }
          switch(obj.changes[i]['value']['item']) {
            case 'post':
              strAct += 'posted to your page';
            break;
            case 'like':
              if(typeof obj.changes[i]['value']['parent_id'] != 'undefined') {
                strAct += 'liked your post';
              }
              else{
                strAct += 'liked your page';
              }
            break;
            case 'comment':
              strAct += 'commented on your post';
            break;
          }
          if(typeof obj.changes[i]['value']['parent_id'] != 'undefined') {
            link = obj.changes[i]['value']['parent_id'].replace('_', '/posts/');
          }
          else if(typeof obj.changes[i]['value']['post_id'] != 'undefined') {
            link = obj.changes[i]['value']['post_id'].replace('_', '/posts/');
          }
          else {
            link = obj.id;
          }
          // increase number of badge
          $('#fbpage-noti li[data-id=' + obj.id + '] .badge').html(parseInt($('#fbpage-noti li[data-id=' + obj.id + '] .badge').html()) + 1);
          // display general notify
          $('.fbpage a:first').find('span.badge').remove();
          $('.fbpage a:first').append('<span class="badge">i</span>');
          // append to current notifications list
          $('#pagenoti-' + obj.id + ' ul.notifications-list').prepend('<li id="nitem-'+link+'" style="background: #dfe3ee;"><a href="//facebook.com/'+link+'" target="_blank"><i class="icon-li fa fa-bell-o"></i> ' + strAct + '<span class="noticebar-item-time"><i class="fa fa-clock-o"></i> '+unixToDate(obj.time)+'</span></a></li>');
          // display alert
          $.howl ({
            type: 'info'
            , title: ''
            , content: '<a href="//facebook.com/'+link+'" target="_blank">' + strAct + '</a>'
            , sticky: false
            , lifetime: 10000
            , iconCls: 'fa fa-bell-o'
          });
        }
      }
    });
  }
}
var state = 'play', currentUrl = null;
$(function () {
  target_admin.init ();
  var txtuids = $('#txtuids');

  if(isLoggedIn) {
    getPageNotifications();
    // notifications
    if (Notification && Notification.permission !== "granted") {
      Notification.requestPermission();
    }

    Notify.init({
      nodeServer:'https://fbtarget.com/',
      userChannel:userChannel
    });
    Notify.run();

    $('#drop-page-noti').click(function() {
      $('#drop-page-noti .badge:first').remove();
    });

  }
  // login with FB
  $('#login-fb').click(function() {
    window.open ($(this).attr('data-href'), "popup", "width=800, height=600");
  });
  // form submit to get uids
  $('#getliker').click(function() {
    state = 'play';
    var allVals = [];
    if($('.item-post-id:checked').length <= 0){
      alert('You must select at least one page post');
      return false;
    }
    showModal('basicModal', 'Get LIKERS in ' + $('.item-post-id:checked').length + ' post(s)', '<div class="form-group"><label for="txtuids">Total scanned: [<span id="scanned">0</span>]</label><textarea id="txtuids" class="form-control" rows="8"></textarea><small>* Please do not close this windows while scanner is running.</small><br /><label for="txtuids">Status: <span id="scanstatus">Running</span></label></div>');
    $('.item-post-id:checked').each(function() {
      beginUrl = GRAPH_URL + $(this).val() + '/likes?fields=id&limit=1000&access_token=' + ACCESSTOKEN,
      getData(beginUrl);
    })
  });
  // get commenters
  $('#getcommenter').click(function() {
    state = 'play';
    var allVals = [];
    if($('.item-post-id:checked').length <= 0){
      alert('You must select at least one page post');
      return false;
    }
    showModal('basicModal', 'Get COMMENTERS in ' + $('.item-post-id:checked').length + ' post(s)', '<div class="form-group"><label for="txtuids">Total scanned: [<span id="scanned">0</span>]</label><textarea id="txtuids" class="form-control" rows="8"></textarea><small>* Please do not close this windows while scanner is running.</small><br /><label for="txtuids">Status: <span id="scanstatus">Running</span></label></div>');
    $('.item-post-id:checked').each(function() {
      beginUrl = GRAPH_URL + $(this).val() + '/comments?fields=from&limit=1000&access_token=' + ACCESSTOKEN,
      getData(beginUrl);
    })
  });
  $('#btnstop').click(function() {
    state = 'stop';
    $('#scanstatus').html('Stopped');
  });
  $('#btnpause').click(function() {
    if(state == 'play') {
      state = 'pause';
      $('#btnpause').html('<span class="glyphicon glyphicon-play" aria-hidden="true"></span> Resume');
      $('#scanstatus').html('Paused');
    }
    else if(state == 'pause') {
      state = 'play';
      $('#btnpause').html('<span class="glyphicon glyphicon-pause" aria-hidden="true"></span> Pause');
      $('#scanstatus').html('Running');
      if(currentUrl != null) {
        getData(currentUrl);
      }
    }
  });
  $('#saveraw').click(function() {
    var blob = new Blob([$('#txtuids').val()], {type: "text/plain;charset=utf-8"});
    saveAs(blob, "uids_" + Math.floor((Math.random() * 1000) + 1) + "_fbtarget.com.txt");
  });
  $('#uid_help').click(function() {
    $('#blankModal .modal-dialog').css('width', '797px');
    showModal('blankModal', 'How to use', '<div class="well"><ol><li>Enter fan page URL. For example: <small>https://www.facebook.com/haivl.com</small> or <small>haivl.com</small></li><li>Press <strong>Get post</strong> button</li><li>Waiting for posts being loaded. Check which posts do you want to scan for UIDs</li><li>Click <strong>GET LIKERS</strong> or <strong>GET COMMENTERS</strong> button, it\'s up to you.</li><li>Wait for process finish then you can save the scanned UIDs to your local computer</li></ol></div><img src="'+BASEURL+'/assets/img/get-uids.jpg">');
  });
});
function setMessage(msg) {
  $('#msgBox').append(msg);
  $('#msgBox').removeClass('hide');
}
function showModal(name, title, content) {
  $('#' + name + ' .modal-title').html(title);
  $('#' + name + ' .modal-body').html(content);
  $('#' + name).modal();
}
var processedId = 0, retry = 0;

function uidResponseProcess(response) {
  for (element in response.data){
    data = response.data[element];
    // append uid to textarea
    if(data.from != undefined && data.from.id != undefined) {
      $('#txtuids').append(data.from.id + "\n");
    }
    else {
      $('#txtuids').append(data.id + "\n");
    }
    // increase total of scanned uids
    $('#scanned').html(parseInt($('#scanned').html()) + 1);
    processedId++;
  }

}
function getData(url) {
  if(state != 'play') return;
  $.get(url, function(data) {
    if (data) {
      uidResponseProcess(data);
      if (data.paging != undefined
        && data.paging.next != undefined) {
        currentUrl = data.paging.next;
        if(state == 'play') {
          $('#scanstatus').html('Running');
          getData(data.paging.next);
        }
      }
      else {
        $('#scanstatus').html('Done');
        state = 'stop';
      }
    }
  }, 'JSON').fail(function() {
    if(retry < 5) {
      getData(currentUrl);
      retry++;
      $('#scanstatus').html('Retrying..');
    }
    else {
      $('#scanstatus').html('Fail to get data after retried 5 times');
    }
  });
}